import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_upgrade_plugin/src/styles/gradientlinear_progress_indicator.dart';
import '../flutter_upgrade_plugin.dart';
import 'styles/circular_progress_indicator.dart';
import 'styles/linear_progress_indicator.dart';

class AppUpgradeDialog extends StatefulWidget {
  ///
  /// 升级标题
  ///
  final String title;

  ///
  /// 标题样式
  ///
  final TextStyle? titleStyle;

  ///
  /// 升级提示内容
  ///
  final String? contents;

  ///
  /// 提示内容样式
  ///
  final TextStyle? contentStyle;

  ///
  /// 中间展示的文字
  ///
  final Widget? center;

  ///
  /// 方向
  ///
  final Axis? direction;

  ///
  /// 下载进度条
  ///
  final Widget? progressBar;

  ///
  ///进度样式
  ///
  final ProgressStyle? progressStyle;

  ///
  /// 进度条颜色
  ///
  final Color? progressBarColor;

  ///
  /// 确认控件
  ///
  final String? okText;

  ///
  /// 确认控件样式
  ///
  final TextStyle? okTextStyle;

  ///
  /// 确认控件背景颜色,2种颜色左到右线性渐变
  ///
  final List<Color>? okBackgroundColors;

  ///
  /// 取消控件
  ///
  final String? cancelText;

  ///
  /// 取消控件样式
  ///
  final TextStyle? cancelTextStyle;

  ///
  /// app安装包下载url,没有下载跳转到应用宝等渠道更新
  ///
  final String? downloadUrl;

  ///
  /// 圆角半径
  ///
  final double borderRadius;

  ///
  /// 是否强制升级,设置true没有取消按钮
  ///
  final bool force;

  ///
  /// ios app id,用于跳转app store
  ///
  final String? iosAppId;

  ///
  /// 指定跳转的应用市场，
  /// 如果不指定将会弹出提示框，让用户选择哪一个应用市场。
  ///
  final AppMarketInfo? appMarketInfo;

  final VoidCallback? onCancel;
  final VoidCallback? onOk;
  final DownloadProgressCallback? downloadProgress;
  final DownloadStatusChangeCallback? downloadStatusChange;

  const AppUpgradeDialog({
    Key? key,
    required this.title,
    required this.contents,
    this.titleStyle,
    this.contentStyle,
    this.progressBar,
    this.progressBarColor,
    this.okText,
    this.okTextStyle,
    this.okBackgroundColors,
    this.cancelText,
    this.cancelTextStyle,
    this.downloadUrl,
    this.borderRadius = 0,
    this.center,
    this.direction,
    this.force = false,
    this.iosAppId,
    this.appMarketInfo,
    this.onCancel,
    this.onOk,
    this.downloadProgress,
    this.downloadStatusChange,
    this.progressStyle,
  }) : super(key: key);

  @override
  State<AppUpgradeDialog> createState() => _AppUpgradeDialogState();
}

class _AppUpgradeDialogState extends State<AppUpgradeDialog> {
  static const String _downloadApkName = 'temp.apk';

  ///
  /// 下载进度
  ///
  double _downloadProgress = 0.0;
  double _downloadCount = 0.0;
  double _downloadTotal = 0.0;
  DownloadStatus _downloadStatus = DownloadStatus.none;

  bool isDownload = false;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: <Widget>[
          _buildInfoWidget(context),
          (_downloadProgress > 0 &&
                  widget.progressStyle != ProgressStyle.normal)
              ? Positioned.fill(child: _buildDownloadProgress())
              : Container(
                  height: 10,
                )
        ],
      ),
    );
  }

  ///
  /// 信息展示widget
  ///
  Widget _buildInfoWidget(BuildContext context) {
    return Container(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          //标题
          _buildTitle(),
          //更新信息
          _buildAppInfo(),

          (isDownload && widget.progressStyle == ProgressStyle.normal)
              ? buildNormalProgress()
              : const SizedBox(),
          //
          // 操作按钮
          isDownload
              ? (widget.progressStyle != ProgressStyle.normal)?Container(
                  padding:const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                  width: double.infinity,
                  child: const Text.rich(
                    textAlign: TextAlign.right,
                    TextSpan(
                        text: '请等待更新完成',
                        style: TextStyle(
                          color: Color(0xff666666),
                        )),
                  ),
                ):const SizedBox()
              : _buildAction()
        ],
      ),
    );
  }

  ///
  /// 构建标题
  ///
  _buildTitle() {
    return Padding(
        padding: EdgeInsets.only(top: 20, bottom: 20),
        child: Text(widget.title ?? '',
            style: widget.titleStyle ?? TextStyle(fontSize: 22)));
  }

  ///
  /// 构建版本更新信息
  ///
  _buildAppInfo() {
    return Container(
        padding: EdgeInsets.only(left: 15, right: 15, bottom: 10),
        height: 220,
        child: SingleChildScrollView(
          child: Html(data: widget.contents ?? ''),
        ));
  }

  ///
  /// 构建取消或者升级按钮
  ///
  _buildAction() {
    return Column(
      children: <Widget>[
        const Divider(
          height: 1,
          color: Color(0xffE5E5E5),
        ),
        Row(
          children: <Widget>[
            widget.force
                ? Container()
                : Expanded(
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Expanded(
                          child:  _buildCancelActionButton(),
                        ),
                         Container(
                           width: 1,
                           color: Color(0xffE5E5E5),
                           height: 45,
                         ),
                        //  Divider(
                        //   height: 20,
                        //
                        //   color: Colors.red,
                        // ),
                      ],
                    ),
                  ),
            Expanded(
              child: _buildOkActionButton(),
            ),
          ],
        ),
      ],
    );
  }

  ///
  /// 取消按钮
  ///
  _buildCancelActionButton() {
    return Ink(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(widget.borderRadius))),
      child: InkWell(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(widget.borderRadius)),
          child: Container(
            height: 45,
            alignment: Alignment.center,
            child: Text(widget.cancelText ?? '以后再说',
                style: widget.cancelTextStyle ?? TextStyle(fontSize: 16)),
          ),
          onTap: () {
            widget.onCancel?.call();
            Navigator.of(context).pop();
          }),
    );
  }

  ///
  /// 确定按钮
  ///
  _buildOkActionButton() {
    var borderRadius =
        BorderRadius.only(bottomRight: Radius.circular(widget.borderRadius));
    var okBackgroundColors = widget.okBackgroundColors ??
        [Theme.of(context).primaryColor, const Color.fromARGB(0, 0, 0, 255)];
    if (widget.force == true) {
      borderRadius = BorderRadius.only(
          bottomRight: Radius.circular(widget.borderRadius),
          bottomLeft: Radius.circular(widget.borderRadius));
    }

    return Ink(
      decoration: BoxDecoration(
          // gradient: LinearGradient(
          //     begin: Alignment.topLeft,
          //     end: Alignment.bottomRight,
          //     colors: (isDownload && widget.force == true)
          //         ? [Color.fromARGB(30, 0, 0, 255), Color(0xd2409eff)]
          //         : okBackgroundColors),
          borderRadius: borderRadius),
      child: InkWell(
        borderRadius: borderRadius,
        child: Container(
          height: 45,
          alignment: Alignment.center,
          child: Text(widget.okText ?? '立即体验',
              style: widget.okTextStyle ?? TextStyle(color: Colors.black,fontWeight: FontWeight.bold,fontSize: 16)),
        ),
        onTap: () {
          _clickOk();
        },
      ),
    );
  }

  ///
  /// 下载进度widget
  ///
  Widget _buildDownloadProgress() {
    return widget.progressBar ?? _buildProgreeStyle();
  }

  Widget _buildProgreeStyle() {
    Widget progressWidget;
    switch (widget.progressStyle) {
      case ProgressStyle.circular:
        progressWidget = CircularProgressIndicatorStyle(
          center: widget.center,
          value: _downloadProgress,
          backgroundColor: Color(0xfff5f5f5f).withOpacity(0.2),
          direction: widget.direction ?? Axis.vertical,
          valueColor: AlwaysStoppedAnimation(widget.progressBarColor ??
              Theme.of(context).primaryColor.withOpacity(0.4)),
        );
        break;
      default:
        progressWidget = LinearProgressIndicatorStyle(
          center: widget.center,
          value: _downloadProgress,
          direction: widget.direction ?? Axis.vertical,
          valueColor: AlwaysStoppedAnimation(widget.progressBarColor ??
              Theme.of(context).primaryColor.withOpacity(0.4)),
          borderRadius: widget.borderRadius,
        );
        break;
    }
    return progressWidget;
  }

  ///
  /// 点击确定按钮
  ///
  _clickOk() async {
    widget.onOk?.call();

    if (Platform.isIOS) {
      //ios 需要跳转到app store更新，原生实现
      FlutterUpgrade.toAppStore(widget.iosAppId ?? '');
      return;
    }
    if (widget.downloadUrl == null || widget.downloadUrl == '') {
      //没有下载地址，跳转到第三方渠道更新，原生实现
      FlutterUpgrade.toMarket(appMarketInfo: widget.appMarketInfo);
      return;
    }
    String path = await FlutterUpgrade.apkDownloadPath;
    _downloadApk(widget.downloadUrl ?? '', '$path/$_downloadApkName');
  }

  ///
  /// 下载apk包
  ///
  _downloadApk(String url, String path) async {
    if (_downloadStatus == DownloadStatus.start ||
        _downloadStatus == DownloadStatus.downloading ||
        _downloadStatus == DownloadStatus.done) {
      showDialog(context: context, builder: (_){
        return Text('当前下载状态：$_downloadStatus,不能重复下载。');
      });
      return;
    }

    _updateDownloadStatus(DownloadStatus.start);
    try {
      var dio = Dio();
      await dio.download(url, path, onReceiveProgress: (int count, int total) {
        if (total == -1) {
          _downloadProgress = 0.01;
        } else {
          widget.downloadProgress?.call(count, total);
          _downloadProgress = count / total.toDouble();
          _downloadCount = count / (1024 * 1024);
          _downloadTotal = total.toDouble() / (1024 * 1024);
        }
        setState(() {
          isDownload = true;
        });
        if (_downloadProgress == 1) {
          //下载完成，跳转到程序安装界面
          _updateDownloadStatus(DownloadStatus.done);
          Navigator.pop(context);
          FlutterUpgrade.installAppForAndroid(path);
          setState(() {
            isDownload = false;
          });
        }
      });
    } catch (e) {
      _downloadProgress = 0;
      _downloadTotal = 0;
      _downloadCount = 0;
      _updateDownloadStatus(DownloadStatus.error, error: e);
    }
  }
  _updateDownloadStatus(DownloadStatus downloadStatus, {dynamic error}) {
    _downloadStatus = downloadStatus;
    widget.downloadStatusChange?.call(_downloadStatus, error: error);
  }


  Widget buildNormalProgress(){
    return  Padding(
      padding:
      const EdgeInsets.symmetric(horizontal: 15, vertical: 20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            height: 6,
            child: GradientLinearProgressBar(
              value: _downloadProgress,
              strokeCapRound: true,
              strokeWidth: 6,
              colors: const [Color(0xff8AC5F8), Color(0xff3981E5)],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 5),
            child: Text.rich(
              TextSpan(
                  text:
                  '下载进度：${_downloadCount.toStringAsFixed(2)}M/${_downloadTotal.toStringAsFixed(2)}M',
                  style: TextStyle(color: Color(0xff999999))),
            ),
          ),
          Container(
            width: double.infinity,
            child: const Text.rich(
              textAlign: TextAlign.right,
              TextSpan(
                  text: '请等待更新完成',
                  style: TextStyle(
                    color: Color(0xff666666),
                  )),
            ),
          ),
        ],
      ),
    );
  }



}
